package com.kakarote.examine.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.service.AdminService;
import com.kakarote.core.feign.examine.entity.*;
import com.kakarote.core.servlet.ApplicationContextHolder;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.BaseUtil;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.examine.constant.*;
import com.kakarote.examine.entity.BO.ExaminePassBO;
import com.kakarote.examine.entity.PO.ExamineRecordLog;
import com.kakarote.examine.entity.PO.*;
import com.kakarote.examine.mapper.ExamineConditionMapper;
import com.kakarote.examine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批条件表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-11-13
 */
@Service("conditionService")
public class ExamineConditionServiceImpl extends BaseServiceImpl<ExamineConditionMapper, ExamineCondition> implements IExamineConditionService, ExamineTypeService {

    @Autowired
    private IExamineRecordLogService examineRecordLogService;

    @Autowired
    private IExamineConditionDataService examineConditionDataService;

    @Autowired
    private IExamineFlowService examineFlowService;

    @Autowired
    private AdminService adminService;


    @Autowired
    private IExamineFlowFinalService examineFlowFinalService;

    @Autowired
    private IExamineRecordService examineRecordService;


    @Autowired
    private IExamineFlowAuthFieldService examineFlowAuthFieldService;

    /**
     * 保存额外的审批流程data对象
     *
     * @param dataSaveBO data
     * @param flowId     审批流程ID
     */
    @Override
    public void saveExamineFlowData(ExamineDataSaveBO dataSaveBO, Long flowId, String batchId) {
        List<ExamineConditionSaveBO> conditionList = dataSaveBO.getConditionList();
        for (ExamineConditionSaveBO conditionSaveBO : conditionList) {
            ExamineCondition examineCondition = new ExamineCondition();
            examineCondition.setConditionName(conditionSaveBO.getConditionName());
            examineCondition.setCreateTime(LocalDateTimeUtil.now());
            examineCondition.setCreateUserId(UserUtil.getUserId());
            examineCondition.setFlowId(flowId);
            examineCondition.setBatchId(batchId);
            examineCondition.setPriority(conditionSaveBO.getSort());
            /*
              保存条件数据
             */
            save(examineCondition);
            /*
              保存条件扩展字段数据
             */
            saveConditionData(conditionSaveBO.getConditionDataList(), examineCondition.getConditionId(), flowId, batchId);
            /*
              保存条件下审批数据
             */
            saveExamineFlow(conditionSaveBO.getExamineDataList(), examineCondition.getConditionId(), batchId);
        }
    }

    /**
     * 通过batchId查询所有flow关联对象
     *
     * @param map     缓存对象
     * @param batchId batchId
     */
    @Override
    public void queryFlowListByBatchId(Map<String, Object> map, String batchId) {
        List<ExamineCondition> conditions = lambdaQuery().eq(ExamineCondition::getBatchId, batchId).list();
        Map<Long, List<ExamineCondition>> collect = conditions.stream().collect(Collectors.groupingBy(ExamineCondition::getFlowId));
        map.put(ExamineTypeEnum.CONDITION.getServerName(), collect);
        List<ExamineConditionData> conditionData = examineConditionDataService.lambdaQuery().eq(ExamineConditionData::getBatchId, batchId).list();
        Map<Long, List<ExamineConditionData>> listMap = conditionData.stream().collect(Collectors.groupingBy(ExamineConditionData::getConditionId));
        map.put("conditionData", listMap);
    }

    /**
     * 查询详情页需要的审批详情
     *
     * @param examineFlow 当前审批流程
     * @param map         缓存的map
     * @return data
     */
    @Override
    @SuppressWarnings("unchecked")
    public ExamineFlowVO createFlowInfo(ExamineFlow examineFlow, Map<String, Object> map, List<UserInfo> allUserList, Long ownerUserId) {
        Map<Long, List<ExamineCondition>> collect = (Map<Long, List<ExamineCondition>>) map.get(ExamineTypeEnum.CONDITION.getServerName());
        List<ExamineCondition> examineConditions = collect.get(examineFlow.getFlowId());
        //条件data对象
        Map<Long, List<ExamineConditionData>> conditionDataMap = (Map<Long, List<ExamineConditionData>>) map.get("conditionData");
        //排序
        examineConditions.sort((Comparator.comparing(ExamineCondition::getPriority)));

        Map<Long, List<ExamineFlow>> flowMap = (Map<Long, List<ExamineFlow>>) map.get("flow");

        ExamineFlowVO examineFlowVO = new ExamineFlowVO();
        examineFlowVO.setName(examineFlow.getName());
        examineFlowVO.setFlowId(examineFlow.getFlowId());
        examineFlowVO.setExamineType(examineFlow.getExamineType());
        examineFlowVO.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
        List<ExamineFlowConditionVO> conditionList = new ArrayList<>();
        for (ExamineCondition examineCondition : examineConditions) {
            ExamineFlowConditionVO examineFlowConditionVO = new ExamineFlowConditionVO();
            examineFlowConditionVO.setSort(examineCondition.getPriority());
            examineFlowConditionVO.setConditionName(examineCondition.getConditionName());
            List<ExamineConditionData> conditionDataList = conditionDataMap.get(examineCondition.getConditionId());
            if (conditionDataList == null) {
                conditionDataList = new ArrayList<>();
            }

            List<ExamineFlowConditionDataVO> ConditionDataVO = conditionDataList.stream().map(collectData -> {
                ExamineFlowConditionDataVO examineFlowConditionDataVO = new ExamineFlowConditionDataVO();
                examineFlowConditionDataVO.setConditionType(collectData.getConditionType());
                examineFlowConditionDataVO.setFieldId(collectData.getFieldId());
                examineFlowConditionDataVO.setName(collectData.getName());
                examineFlowConditionDataVO.setType(collectData.getType());
                examineFlowConditionDataVO.setFieldName(collectData.getFieldName());
                examineFlowConditionDataVO.setBackupValue(collectData.getValue());
                examineFlowConditionDataVO.setGroupId(collectData.getGroupId());
                if (Objects.equals(collectData.getConditionType(), ConditionTypeEnum.PERSONNEL.getType())) {
                    ExamineGeneralBO examineGeneralBO = JSON.parseObject(collectData.getValue(), ExamineGeneralBO.class);
                    Map<String, Object> dataMap = this.convertDataMapByExamineGeneralBO(examineGeneralBO);
                    examineFlowConditionDataVO.setValues(dataMap);
                } else {
                    examineFlowConditionDataVO.setValues(JSON.parseArray(collectData.getValue(), String.class));
                }
                return examineFlowConditionDataVO;
            }).collect(Collectors.toList());

            Map<Long, List<ExamineFlowConditionDataVO>> groupConditionData = ConditionDataVO.stream()
                    .collect(Collectors.groupingBy(ExamineFlowConditionDataVO::getGroupId));

            //按照groupId排序
            groupConditionData = groupConditionData.entrySet().stream().sorted(Map.Entry.comparingByKey())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

            List<List<ExamineFlowConditionDataVO>> conditionDataVOList = new ArrayList<>();
            for (Map.Entry<Long, List<ExamineFlowConditionDataVO>> entry : groupConditionData.entrySet()) {
                conditionDataVOList.add(entry.getValue());
            }


            //设置条件自定义字段数据
            examineFlowConditionVO.setConditionDataList(conditionDataVOList);


            List<ExamineFlow> examineFlows = Optional.ofNullable(flowMap.get(examineCondition.getConditionId())).orElse(new ArrayList<>());
            //排序，升序
            examineFlows.sort((Comparator.comparing(ExamineFlow::getSort)));
            List<ExamineFlowVO> examineFlowVOList = new ArrayList<>();
            for (ExamineFlow flow : examineFlows) {
                ExamineTypeService examineTypeService = ApplicationContextHolder.getBean(ExamineTypeEnum.valueOf(flow.getExamineType()).getServerName());

                ExamineFlowVO flowInfo = examineTypeService.createFlowInfo(flow, map, allUserList, ownerUserId);

                List<ExamineFlowAuthField> authFields = examineFlowAuthFieldService.lambdaQuery()
                        .eq(ExamineFlowAuthField::getFlowId, flowInfo.getFlowId())
                        .list();


                List<ExamineFlowAuthField> authFieldList = authFields.stream().filter(e -> e.getParentId() == null).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(authFieldList)) {
                    for (ExamineFlowAuthField authField : authFieldList) {
                        if (authField.getHasChildren() == 1) {
                            List<ExamineFlowAuthField> collect1 = authFields.stream().filter(e -> e.getParentId() != null).filter(e -> e.getParentId().equals(authField.getId())).collect(Collectors.toList());

                            authField.setFieldExtendList(collect1);
                        }
                    }
                    List<ExamineFieldAuthBO> fieldAuthBOS = JSONUtil.toList(JSONUtil.parseArray(authFieldList), ExamineFieldAuthBO.class);
                    flowInfo.setFieldAuthList(fieldAuthBOS);
                } else {
                    flowInfo.setFieldAuthList(new ArrayList<>());
                }

                examineFlowVOList.add(flowInfo);
            }
            examineFlowConditionVO.setExamineDataList(examineFlowVOList);
            conditionList.add(examineFlowConditionVO);
        }
        examineFlowVO.setConditionList(conditionList);
        return examineFlowVO;
    }


    /**
     * 补充用户部门信息
     *
     * @param examineGeneralBO bo
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2020/12/17 13:50
     **/
    private Map<String, Object> convertDataMapByExamineGeneralBO(ExamineGeneralBO examineGeneralBO) {
        Map<String, Object> dataMap = new HashMap<>(3);
        dataMap.put(ExamineConst.USER_LIST, UserCacheUtil.getSimpleUsers(examineGeneralBO.getUserList()));
        List<Map<String, Object>> deptMapList = new ArrayList<>();
        List<Long> deptList = examineGeneralBO.getDeptList();
        if (CollUtil.isNotEmpty(deptList)) {
            deptList.forEach(deptId -> {
                Map<String, Object> deptMap = new HashMap<>(2);
                deptMap.put(ExamineConst.DEPT_ID, deptId);
                deptMap.put(ExamineConst.DEPT_NAME, UserCacheUtil.getDeptName(deptId));
                deptMapList.add(deptMap);
            });
        }
        dataMap.put(ExamineConst.DEPT_LIST, deptMapList);
        dataMap.put(ExamineConst.ROLE_LIST, examineGeneralBO.getRoleList());
        return dataMap;
    }

    /**
     * 保存审批流程数据
     */
    private void saveExamineFlow(List<ExamineDataSaveBO> dataList, Long conditionId, String batchId) {
        int i = 1;
        for (ExamineDataSaveBO dataSaveBO : dataList) {
            ExamineTypeEnum examineTypeEnum = ExamineTypeEnum.valueOf(dataSaveBO.getExamineType());
            ExamineFlow examineFlow = new ExamineFlow();
            examineFlow.setExamineType(dataSaveBO.getExamineType());
            examineFlow.setExamineId(0L);
            examineFlow.setName(dataSaveBO.getName());
            examineFlow.setConditionId(conditionId);
            examineFlow.setCreateTime(LocalDateTimeUtil.now());
            examineFlow.setCreateUserId(UserUtil.getUserId());
            examineFlow.setBatchId(batchId);
            examineFlow.setExamineErrorHandling(dataSaveBO.getExamineErrorHandling());
            examineFlow.setSort(i++);
            examineFlowService.save(examineFlow);

            List<ExamineFieldAuthBO> fieldAuthList = dataSaveBO.getFieldAuthList();
            if (fieldAuthList != null) {
                List<ExamineFlowAuthField> flowAuthFields = new ArrayList<>();
                for (ExamineFieldAuthBO examineFieldAuthBO : fieldAuthList) {

                    ExamineFlowAuthField flowAuthField = new ExamineFlowAuthField();
                    flowAuthField.setId(BaseUtil.getNextId());
                    flowAuthField.setFlowId(examineFlow.getFlowId());
                    flowAuthField.setAuthLevel(examineFieldAuthBO.getAuthLevel());
                    flowAuthField.setFieldId(examineFieldAuthBO.getFieldId());
                    flowAuthField.setFieldName(examineFieldAuthBO.getFieldName());
                    flowAuthField.setExamineId(0L);
                    flowAuthField.setCreateTime(new Date());
                    flowAuthField.setCreateUserId(UserUtil.getUserId());
                    flowAuthField.setLabel(examineFieldAuthBO.getLabel());
                    flowAuthField.setTableLevel(examineFieldAuthBO.getTableLevel());
                    List<ExamineFieldAuthBO> fieldExtendList = examineFieldAuthBO.getFieldExtendList();
                    if (ObjectUtil.isNotEmpty(fieldExtendList)) {
                        flowAuthField.setHasChildren(1);
                        for (ExamineFieldAuthBO fieldAuthBO : examineFieldAuthBO.getFieldExtendList()) {
                            ExamineFlowAuthField extendField = new ExamineFlowAuthField();
                            extendField.setId(BaseUtil.getNextId());
                            extendField.setFlowId(examineFlow.getFlowId());
                            extendField.setAuthLevel(fieldAuthBO.getAuthLevel());
                            extendField.setFieldId(fieldAuthBO.getFieldId());
                            extendField.setFieldName(fieldAuthBO.getFieldName());
                            extendField.setExamineId(0L);
                            extendField.setCreateTime(new Date());
                            extendField.setCreateUserId(UserUtil.getUserId());
                            extendField.setLabel(fieldAuthBO.getLabel());
                            extendField.setHasChildren(0);
                            extendField.setParentId(flowAuthField.getId());
                            flowAuthFields.add(extendField);
                        }
                    }
                    flowAuthFields.add(flowAuthField);
                }
                examineFlowAuthFieldService.saveBatch(flowAuthFields);
            }

            ExamineTypeService examineTypeService = ApplicationContextHolder.getBean(examineTypeEnum.getServerName());
            examineTypeService.saveExamineFlowData(dataSaveBO, examineFlow.getFlowId(), batchId);
        }
    }

    private void saveConditionData(List<List<ExamineConditionDataSaveBO>> conditionDataSaveBOList, Long conditionId, Long flowId, String batchId) {
        if (conditionDataSaveBOList.size() == 0) {
            return;
        }
        List<ExamineConditionData> conditionDataList = new ArrayList<>();

        for (List<ExamineConditionDataSaveBO> examineConditionDataSaveBO : conditionDataSaveBOList) {
            Long groupId = BaseUtil.getNextId();
            for (ExamineConditionDataSaveBO dataSaveBO : examineConditionDataSaveBO) {
                ExamineConditionData conditionData = new ExamineConditionData();
                conditionData.setConditionId(conditionId);
                conditionData.setFlowId(flowId);
                conditionData.setConditionType(dataSaveBO.getConditionType());
                Long fieldId = dataSaveBO.getFieldId();
                conditionData.setFieldId(fieldId != null ? fieldId : Long.valueOf(0));
                conditionData.setName(dataSaveBO.getName());
                String fieldName = dataSaveBO.getFieldName();
                conditionData.setFieldName(fieldName != null ? fieldName : "");
                Integer type = dataSaveBO.getType();
                conditionData.setType(type != null ? type : 0);
                conditionData.setBatchId(batchId);
                conditionData.setValue(JSON.toJSONString(dataSaveBO.getValues()));
                conditionData.setGroupId(groupId);
                conditionDataList.add(conditionData);
            }
        }
        examineConditionDataService.saveBatch(conditionDataList, Const.BATCH_SAVE_SIZE);
    }

    /**
     * 查询条件审批下的审批流程
     *
     * @param examineFlow  当前流程
     * @param conditionMap 条件entity
     * @return data
     */
    @Override
    public ExamineFlow queryNextExamineFlowByCondition(ExamineFlow examineFlow, Map<String, Object> conditionMap) {
        List<ExamineCondition> conditionList = lambdaQuery().eq(ExamineCondition::getFlowId, examineFlow.getFlowId()).orderByAsc(ExamineCondition::getPriority).list();
        Map<Long, List<ExamineConditionData>> conditionDataMap = examineConditionDataService.lambdaQuery().eq(ExamineConditionData::getFlowId, examineFlow.getFlowId()).list().stream().collect(Collectors.groupingBy(ExamineConditionData::getConditionId));
        Long conditionId = null;
        UserInfo userInfo = UserCacheUtil.getUserInfo(TypeUtils.castToLong(conditionMap.get(ExamineConst.CREATE_USER_ID)));
        for (ExamineCondition examineCondition : conditionList) {
            List<ExamineConditionData> conditionDataList = conditionDataMap.get(examineCondition.getConditionId());
            /*
              当前条件审批没有条件，默认直接通过
             */
            if (conditionDataList == null || conditionDataList.size() == 0) {
                conditionId = examineCondition.getConditionId();
                break;
            }
            boolean isPass = handleExamineConditionData(conditionDataList, conditionMap, userInfo);
            if (isPass) {
                conditionId = examineCondition.getConditionId();
                break;
            }
        }
        if (conditionId == null) {
            //审批找不到用户或者条件均不满足时怎么处理 1 自动通过 2 管理员审批
            if (examineFlow.getExamineErrorHandling() == 1) {
                /*
                  当前流程自动通过，去查询下层审批
                 */
                return examineFlowService.queryNextExamineFlow(examineFlow.getExamineId(), examineFlow.getFlowId(), conditionMap);
            }
            /*
              当前流程由管理员审批
             */
            return examineFlow.setExamineType(6);
        }
        ExamineFlow nextExamineFlow = queryExamineFlow(conditionId, conditionMap);
        if (nextExamineFlow == null) {
            /*
               当前流程自动通过，去查询下层审批
            */
            return examineFlowService.queryNextExamineFlow(examineFlow.getExamineId(), examineFlow.getFlowId(), conditionMap);
        }
        return nextExamineFlow;
    }

    @Override
    public boolean handleExamineConditionData(List<ExamineConditionData> conditionDataList, Map<String, Object> conditionMap, UserInfo userInfo) {

        Map<Long, List<ExamineConditionData>> collect = conditionDataList.stream().collect(Collectors.groupingBy(ExamineConditionData::getGroupId));

        collect = collect.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        for (Long groupId : collect.keySet()) {
            List<ExamineConditionData> examineConditionDataList = collect.get(groupId);
            boolean isPass = true;
            for (ExamineConditionData conditionData : examineConditionDataList) {
                ConditionTypeEnum conditionTypeEnum = ConditionTypeEnum.valueOf(conditionData.getConditionType());
                List<String> valueList = new ArrayList<>();
                ExamineGeneralBO examineGeneralBO = null;
                if (ConditionTypeEnum.PERSONNEL.equals(conditionTypeEnum)) {
                    String value;
                    if (conditionData.getBackupValue() != null) {
                        value = conditionData.getBackupValue();
                    } else {
                        value = conditionData.getValue();
                    }
                    examineGeneralBO = JSON.parseObject(JSON.parse(value).toString(), ExamineGeneralBO.class);
                    if (examineGeneralBO == null) {
                        continue;
                    }
                } else {
                    valueList = JSON.parseArray(conditionData.getValue(), String.class);
                    if (valueList.size() == 0) {
                        continue;
                    }
                }
                if (!conditionMap.containsKey(conditionData.getFieldName()) && !ConditionTypeEnum.PERSONNEL.equals(conditionTypeEnum)) {
                    isPass = false;
                    break;
                }
                String fieldValue = Optional.ofNullable(conditionMap.get(conditionData.getFieldName())).orElse("").toString();
                if (StrUtil.isEmpty(fieldValue)) {
                    fieldValue = "0";
                }
                switch (conditionTypeEnum) {
                    case EQ: {
                        //预设的值
                        BigDecimal value = new BigDecimal(valueList.get(0));
                        //用户输入的值
                        BigDecimal data = new BigDecimal(fieldValue);
                        if (!(data.compareTo(value) == 0)) {
                            isPass = false;
                        }
                        break;
                    }
                    case GT: {
                        //预设的值
                        BigDecimal value = new BigDecimal(valueList.get(0));
                        //用户输入的值
                        BigDecimal data = new BigDecimal(fieldValue);
                        if (!(data.compareTo(value) > 0)) {
                            isPass = false;
                        }
                        break;
                    }
                    case GE: {
                        //预设的值
                        BigDecimal value = new BigDecimal(valueList.get(0));
                        //用户输入的值
                        BigDecimal data = new BigDecimal(fieldValue);
                        if (!(data.compareTo(value) >= 0)) {
                            isPass = false;
                        }
                        break;
                    }
                    case LT: {
                        //预设的值
                        BigDecimal value = new BigDecimal(valueList.get(0));
                        //用户输入的值
                        BigDecimal data = new BigDecimal(fieldValue);
                        if (!(data.compareTo(value) < 0)) {
                            isPass = false;
                        }
                        break;
                    }
                    case LE: {
                        //预设的值
                        BigDecimal value = new BigDecimal(valueList.get(0));
                        //用户输入的值
                        BigDecimal data = new BigDecimal(fieldValue);
                        if (!(data.compareTo(value) <= 0)) {
                            isPass = false;
                        }
                        break;
                    }
                    case AMONG: {
                        /*
                          介于两者之前，共需要4个值
                          0、 开始值 1、 比较方式 （1 小于 2 小于等于） 2、比较方式 （1 小于 2 小于等于）3、结束值
                         */
                        if (valueList.size() != 4) {
                            throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
                        }
                        BigDecimal startValue = new BigDecimal(valueList.get(0));
                        BigDecimal endValue = new BigDecimal(valueList.get(3));
                        //用户输入的值
                        BigDecimal data = new BigDecimal(fieldValue);
                        boolean start = "2".equals(valueList.get(1)) ? startValue.compareTo(data) <= 0 : startValue.compareTo(data) < 0;
                        boolean end = "2".equals(valueList.get(2)) ? data.compareTo(endValue) <= 0 : data.compareTo(endValue) < 0;
                        if (!(start && end)) {
                            isPass = false;
                        }
                        break;
                    }
                    case PERSONNEL: {
                        Boolean userPass = Boolean.TRUE;
                        Boolean deptPass = Boolean.TRUE;
                        Boolean rolePass = Boolean.TRUE;
                        List<String> deptList = examineGeneralBO.getDeptList().stream().map(Object::toString).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(deptList) && !deptList.contains(userInfo.getDeptId().toString())) {
                            userPass = Boolean.FALSE;
                        }

                        List<String> userList = examineGeneralBO.getUserList().stream().map(Object::toString).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(userList) && !userList.contains(userInfo.getUserId().toString())) {
                            deptPass = Boolean.FALSE;
                        }

                        List<String> roleIds = userInfo.getRoles().stream().map(Object::toString).collect(Collectors.toList());
                        //Collections.disjoint(list1,list2) false: 有交集 true: 没有交集
                        List<String> roleList = examineGeneralBO.getRoleList().stream().map(Object::toString).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(roleList) && Collections.disjoint(roleList, roleIds)) {
                            rolePass = Boolean.FALSE;
                        }

                        if (ObjectUtil.isEmpty(deptList) && ObjectUtil.isEmpty(userList) && ObjectUtil.isEmpty(roleList)) {
                            isPass = true;
                        } else {
                            if (ObjectUtil.isEmpty(roleList)) {
                                rolePass = Boolean.FALSE;
                            }
                            if (ObjectUtil.isEmpty(deptList) && ObjectUtil.isEmpty(userList)) {
                                userPass = Boolean.FALSE;
                                deptPass = Boolean.FALSE;
                            }

                            isPass = (userPass && deptPass) || rolePass;
                        }
                        break;
                    }
                    case CONTAIN: {
                        String data = conditionMap.get(conditionData.getFieldName()).toString();
                        data = data.replaceAll("\\[", "").replaceAll("\\]", "");
                        List<String> dataList = StrUtil.splitTrim(data, Const.SEPARATOR);
                        //Collections.disjoint(list1,list2) false: 有交集 true: 没有交集
                        if (Collections.disjoint(valueList, dataList)) {
                            isPass = false;
                        }
                        break;
                    }
                    case EQUALS: {
                        String data = conditionMap.get(conditionData.getFieldName()).toString();
                        data = data.replaceAll("\\[", "").replaceAll("\\]", "");
                        List<String> dataList = StrUtil.splitTrim(data, Const.SEPARATOR);
                        //Collections.disjoint(list1,list2) false: 有交集 true: 没有交集\
                        boolean isSameSize = valueList.size() == dataList.size();
                        if (!isSameSize || !valueList.containsAll(dataList)) {
                            isPass = false;
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
            if (isPass) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查询当前条件下审批流
     *
     * @param conditionId 条件ID
     * @return data
     */
    private ExamineFlow queryExamineFlow(Long conditionId, Map<String, Object> conditionMap) {
        if (conditionId == null) {
            return null;
        }
        ExamineFlow examineFlow = examineFlowService.lambdaQuery().eq(ExamineFlow::getConditionId, conditionId).gt(ExamineFlow::getSort, 0).orderByAsc(ExamineFlow::getSort).one();
        if (examineFlow == null) {
            return null;
        }
        if (examineFlow.getExamineType().equals(ExamineTypeEnum.CONDITION.getType())) {
            return queryNextExamineFlowByCondition(examineFlow, conditionMap);
        }
        return examineFlow;
    }

    /**
     * 获取可执行的审批流程
     *
     * @param examineFlow   审批流程
     * @param examineRecord 审批记录
     * @param dataMap       审批条件数据
     * @return 可用的审批流程
     */
    @Override
    public ExamineFlow getAvailableFlow(ExamineFlow examineFlow, ExamineRecord examineRecord, Map<String, Object> dataMap) {
        QueryWrapper<ExamineFlow> flowQueryWrapper = new QueryWrapper<>();
        flowQueryWrapper.eq("batch_id", examineFlow.getBatchId());
        flowQueryWrapper.ne("condition_id", 0);
        flowQueryWrapper.select("condition_id");

        List<String> conditionIds = examineFlowService.listObjs(flowQueryWrapper, Object::toString);

        if (ObjectUtil.isNotEmpty(conditionIds)) {
            List<ExamineConditionData> list = examineConditionDataService.lambdaQuery().in(ExamineConditionData::getConditionId, conditionIds).list();

            //判断有无条件审核，如果有获取相应数据
            if (ObjectUtil.isNotEmpty(list)) {
                if (dataMap == null) {
                    dataMap = new HashMap<>(8);
                    List<String> fieldList = list.stream().map(ExamineConditionData::getFieldName).filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
                    fieldList.removeIf(StrUtil::isEmpty);
                    if (CollUtil.isNotEmpty(fieldList)) {
                        ExamineModuleService moduleService = ApplicationContextHolder.getBean(ExamineEnum.parseModule(examineRecord.getLabel()).getServerName());
                        dataMap = moduleService.getConditionMap(examineRecord.getLabel(), examineRecord.getTypeId(), examineRecord.getRecordId());
                    }
                }
            }
            if (dataMap == null) {
                dataMap = new HashMap<>(8);
            }
            dataMap.put(ExamineConst.CREATE_USER_ID, examineRecord.getCreateUserId());
            ExamineFlow examineFlow1 = queryNextExamineFlowByCondition(examineFlow, dataMap);
            if (examineFlow1 != null) {
                if (examineFlow1.getExamineType().equals(0)) {
                    return getAvailableFlow(examineFlow1, examineRecord, dataMap);
                }
                return examineFlow1;
            } else {
                return examineFlow;
            }

        }
        return examineFlow;
    }

    /**
     * 处理当前节点
     *
     * @param examineFlow 当前处理节点
     * @param recordId    审核记录ID
     * @param data        特殊处理所需数据(具体看实现类)
     * @param examine     审核对象
     * @param init        是否初始化
     * @return data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject disposeFlow(ExamineFlow examineFlow, Long recordId, Object data, Examine examine, boolean init) {
        ExamineRecord examineRecord = examineRecordService.getById(recordId);
        Integer maxSort = examineFlowFinalService.getMaxSort(recordId, examineRecord.getExamineId());

        ExamineFlowFinal examineFlowFinal = new ExamineFlowFinal();
        examineFlowFinal.setName(examineFlow.getName());
        examineFlowFinal.setExamineType(examineFlow.getExamineType());
        examineFlowFinal.setFlowId(examineFlow.getFlowId());
        examineFlowFinal.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
        examineFlowFinal.setCreateTime(new Date());
        examineFlowFinal.setCreateUserId(UserUtil.getUserId());
        examineFlowFinal.setExamineId(examineRecord.getExamineId());
        examineFlowFinal.setRecordId(recordId);
        examineFlowFinal.setType(1);
        examineFlowFinal.setSort(maxSort + 1);
        examineFlowFinalService.save(examineFlowFinal);

        LocalDateTime examineTime = LocalDateTimeUtil.now();

        ExamineRecordLog createRecordLog = new ExamineRecordLog();
        createRecordLog.setFlowId(examineFlow.getFlowId());
        createRecordLog.setCreateTime(examineTime);
        createRecordLog.setCreateUserId(UserUtil.getUserId());
        createRecordLog.setExamineId(examineRecord.getExamineId());
        createRecordLog.setExamineStatus(ExamineStatusEnum.PASS.getStatus());
        createRecordLog.setRecordId(examineRecord.getRecordId());
        createRecordLog.setExamineTime(examineTime);
        createRecordLog.setSort(0);
        createRecordLog.setType(1);
        createRecordLog.setBatchId(IdUtil.simpleUUID());
        createRecordLog.setRemarks("条件节点,自动通过");
        examineRecordLogService.save(createRecordLog);

        Long createUserId = examineRecord.getCreateUserId();
        UserInfo userInfo = UserCacheUtil.getUserInfo(createUserId);

        Integer examineStatus = examineRecordService.auditExaminePass(createRecordLog, examineRecord, userInfo, ExaminePassBO.builder().init(init).dataMap((Map<String, Object>) data).build(), examineTime);

        return new JSONObject().putOpt("status", examineStatus);
    }


}
